/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccstore.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.unitn.science.matr155863_148346_145963.bccstore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccstore.items.Commission;
import it.unitn.science.matr155863_148346_145963.bccstore.items.CreatePDF;
import it.unitn.science.matr155863_148346_145963.bccstore.items.Product;
import it.unitn.science.matr155863_148346_145963.bccstore.items.User;
import java.util.Date;
import java.util.Random;
import javax.servlet.UnavailableException;
import org.apache.log4j.Logger;
/**
 *
 * @author berto
 */
public class ExecutePurchaseSRV extends HttpServlet {

    private DBManager db;
    private static Logger log = Logger.getLogger(ExecutePurchaseSRV.class);
    private Object monitor = new Object();
  
    @Override
    public void init() throws UnavailableException{
            db=(DBManager)super.getServletContext().getAttribute("db_manager");
    }    
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idString = request.getParameter("id");
        String strQuantita = request.getParameter("quantity");
        String address="/contents/user/DetailsPurchase";
        try {
            Integer idProd = Integer.parseInt(idString);
            Integer quantitaInserita = Integer.parseInt(strQuantita);
            User buyer=(User) request.getSession().getAttribute("user");
                User seller=db.getSellerOf(idProd);
                Product prod=effettuaAcquisto(idProd,quantitaInserita);
                if(prod!=null){
                    Long time=new Date().getTime();
                    Random rd=new Random(time);

                      String date=new Date(time).toString().replace(" ", "_");
                    date=date.replace(" ", "_");
                    date=date.replace(":", "-");
                    
                    String fileName=buyer.getUsername()+"_"+rd.nextLong()+"_"+date+".pdf";

                   
                    Commission commission=new Commission(null, 
                            buyer.getId(), seller.getId(),
                            buyer.getFirstName(),buyer.getLastName(),buyer.getUsername(), 
                            seller.getFirstName(), seller.getLastName(),seller.getUsername(),
                            idProd,prod, quantitaInserita, prod.getPrice(),
                            prod.getUmId(),prod.getUmName(),
                            fileName, time);
                    Integer commissionId=db.addCommission(commission);
                    commission.setId(commissionId);
                    request.getSession().setAttribute("commission", commission);
                    try{
                        CreatePDF.createPDF(commission,this.getServletContext().getRealPath("/"));
                        request.getSession().setAttribute("order_state", 0);
                    }catch(Exception ex){
                        //throw new RuntimeException(ex);
                        log.error("Error diuring creation of bill: "+commission.getId()+"\n"+ex);
                        request.getSession().setAttribute("order_state", 1);
                    }
                }else{
                    //Ordine non eseguito
                    request.getSession().setAttribute("order_state", 2);
                }
        }catch(Exception ex){
            log.error(ex);
            address="/contents/public/errorPage.html";
        } finally {            
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+address));
            
        }
    }
    
    private Product effettuaAcquisto(int idInt, int quantitaInserita) {
        synchronized(monitor){
            Product prod= db.getProduct(idInt);
            if (prod != null){
                if(prod.getQuantity()>= quantitaInserita){
                    prod=db.setQuantityProduct(prod.getQuantity() - quantitaInserita,idInt);
                    return prod;
                }
            }  
        }
        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
